from sanic import Sanic
from sanic.exceptions import NotFound
from sanic.response import json

from sanicdb import SanicDB

from biz_code.component import on_setup_config
from biz_code.component import on_load_a_d_function
from biz_code.component.comm.redis_util import Redis
from biz_code.component.comm import public_utils

app = Sanic(name="a_d_frame")


def init_connection_pool():
    # 加载mysql
    app.auto_commit_mysql_conn = SanicDB(*on_setup_config.mysql_config_list, sanic=app,
                                         autocommit=True,
                                         **on_setup_config.config["mysql"]
                                         )

    app.hand_commit_mysql_conn = SanicDB(*on_setup_config.mysql_config_list, sanic=app,
                                         autocommit=False, **on_setup_config.config["mysql"]
                                         )



@app.exception(NotFound)
def notfunderror(request, notfunderrormsg):
    return json({"code": 404, "msg": "url is not fund"})


# 加载入口
def load_entry():
    from .entry_server_api import api_blu
    from .entry_server_admin import admin_blu
    from .entry_server_admin_login import admin_login_blu
    # from .entry_server_user import user_blu
    # from .entry_server_login import login_blu
    app.blueprint(api_blu)
    app.blueprint(admin_blu)
    app.blueprint(admin_login_blu)
    # app.blueprint(user_blu)
    # app.blueprint(login_blu)


def create_sanic_app():
    init_connection_pool()

    # 加载入口
    load_entry()

    # 加载a代码
    app.func_map = on_load_a_d_function.get_a_function()
    return app


@app.listener("before_server_start")
async def before_server_start(request, loop):

    # 初始化redis连接池
    request.redis_pool = await Redis().get_redis_pool()

    # 加载 mysql 参数
    await public_utils.load_sys_params(request, request.auto_commit_mysql_conn)
